<?php
namespace control;
// 故障统计
class aftermarketStatisticsClass extends adIndexClass
{

	private const page           = 'aftermarketStatistics';       # 权限
	private const table          = 'aftermarket';
	private const tableTarget    = 'material';
	private const title          = '故障统计';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'typeName'          => [
                        'name'  => '产品分类',
                        'width' => 200,
                    ],
                    'name' => [
                        'name'  => "产品名称",
                        'width' => 300,
                    ],
                    'type'  => [
                        'name'  => "故障类型",
                        'width' => 200,
                    ],
                    'level'  => [
                        'name'  => "故障等级",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'times'  => [
                        'name'  => "报修次数",
                        'width' => 200,
                    ],
                    'types'         => [
                        'name'  => '故障次数',
                        'width' => 200,
                    ],
                    'rate'          => [
                        'name'  => '故障占比 (%)',
                        'width' => 200,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "日期" => text(['name' => 'date', 'class' => 'text width200', 'laydate' => ['range' => '~', 'type' => 'date'],]),
                    "产品分类"   => materialClass::typeSelect(name: 'typeId'),
                    '产品名称' => text(["name" => "name"]),
                ],
                [
                    '故障类型'  => select(["name" => "type", 'option' => explode('，', para('aftermarketType'))]),
                    "故障等级" => select(["name" => "level", 'option' => explode('，', para('aftermarketLevel'))]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

	/*列表页-查询条件*/
	public function home(): string
	{
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."'})\">导出</span>";
        }
        if ($this->power(self::page, "see")) {
            $button .= "<span onclick=\"layer('" . self::page . "', 'paretoChart', {id:'" . suiji() . "'})\" class='spanButton'>帕累托图</span>\n";
        }
		return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
	}

	public function homeSearch(): bool|string
	{
		//查询结果
		$where = ' 1=1 ';
		$equal = [
			'type'  => $this->post('type'),
			'level' => $this->post('level'),
			'coid'  => self::$coid,
		];
		$like  = [
		];
		//生成子查询语句
		$targetWhere = search([
			"="    => [
				'coid'   => self::$coid,
			],
			"like" => [
				'code' => $this->post('eqCode'),
				'name' => $this->post('name'),
                'typePath' => $this->post('typeId'),
			],
		]);
		if ($targetWhere) {
			$where .= " and targetId IN (SELECT id  FROM `" . self::tableTarget . "` WHERE 1=1 $targetWhere) ";
		}
		$where .= search([
			"="    => $equal,
			"like" => $like,
		]);
		if ($this->post('date')) {
			$where .= self::timeComparison($this->post('date'));
		}
		$fieldArr                      = self::resolveField([
			'field' => '`id`, `coid`, `khid`, `classify`, `workFlow`, `targetId`, `orderNo`, `type`, `level`, `emergency`, `stid`, `state`, `updateTime`, `time`',
			'group' => 'type',
		]);
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
		$page                          = $this->page([
			'field' => $fieldArr['field'],
			"table" => self::table,
			"where" => $where . $fieldArr['group'],
			"order" => $orderBy['orderBy'],
		]);
		$_SESSION[self::page]['where'] = $where;
		$_SESSION[self::page]['sql']   = $page['sql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
        );
		//获取记录
		foreach ($page['array'] as $array) {
			$material     = query(self::tableTarget, " id = '$array[targetId]' ", 'typeId, typeName, name');
			$twhere       = $where . " AND targetId = '{$array['targetId']}' ";
			$mwhere       = $where . " AND targetId = '{$array['targetId']}' AND type = '{$array['type']}' ";
            $times        = static::total([
                'table' => self::table,
                'where' => $twhere,
            ]);
			$types        = static::total([
				'table' => self::table,
				'where' => $mwhere,
			]);
			$rate         = ($types / $times * 100) . '%';
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'typeName':
                    case 'name':
                        $row[] = $material[$key];
                        break;
                    case 'times':
                        $row[] = $times;
                        break;
                    case 'types':
                        $row[] = $types;
                        break;
                    case 'rate':
                        $row[] = $rate;
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
		}
        $times        = static::total([
            'table' => self::table,
            'where' => $where,
        ]);
        $total    = [
            'times'        => $times,
            'types'   => $times,
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
		//返回
		$json['html'] = "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;

		return json_encode($json, 320);
	}

	/**
	 * 编辑
	 */
	public function paretoChart(): bool|string
	{
		$endMoon   = date("Y-m-d");
		$startMoon = date("Y-m-d", strtotime('-1 month'));
		$dateHtml  = select(["name" => "type", 'class' => 'select', "title" => "故障类型", 'option' => explode('，', para('aftermarketType'))]) . text([
				"name"    => "date",
				"title"   => "日期",
				"class"   => "text text-data right contour width200 search-text",
				"value"   => $startMoon . ' ~ ' . $endMoon,
				'laydate' => [
					'range' => '~', 'type' => 'date',
					'done'  => "function(value, date, endDate){return searchFormSub('" . $this->get('cla') . "', 'paretoChartData')}",
				],
			]);
		$html      = <<<EOT
<style>
.paretoChartDataBox{margin: 20px;float: left;line-height: 34px;}
.paretoChartDataBox .select{    height: 28px;margin-right: 15px}
.search-ico{position: absolute;left: 361px;}
#paretoChartDataHtml{margin-top: 50px;}
</style>
<form name='paretoChartDataForm' onsubmit="return searchFormSub('{$this->get('cla')}', 'paretoChartData')">
		<div class="paretoChartDataBox">
			$dateHtml
			<span class="search-ico right" onclick="return searchFormSub('{$this->get('cla')}', 'paretoChartData')"></span>
		</div>
</form>
<div id='paretoChartDataHtml' class='data-box-show'>数据查询中。。。</div>
<script src='/static/javascript/echarts.min.js'></script>
<script>
    $(function(){searchForm('{$this->get('cla')}', 'paretoChartData', 1)});
</script>
EOT;
		//返回
		return $this->layer(["title" => "故障原因分析", "height" => 450, "width" => 1000, "html" => $html]);
	}

	public function paretoChartData()
	{
		$where = ' 1=1 ';
		$where .= search([
			"=" => [
				'coid' => self::$coid,
				'type' => $this->post('type'),
			],
		]);
		if ($this->post('date')) {
			$where .= self::timeComparison($this->post('date'));
		}
		$xArray    = explode('，', para('aftermarketType'));
		$xData     = json_encode($xArray, 320);
		$typeArray = $rateArray = [];
		$typeRate  = 0;
		// 总故障率
		$total = static::total([
			'table' => self::table,
			'where' => $where,
		]);
		foreach ($xArray as $type) {
			$typeTotal   = static::total([
				'table' => self::table,
				'where' => " $where and `type` = '$type'",
			]);
			$rate        = $total>0?$typeTotal / $total * 100:0;
			$typeRate    += $rate;
			$rateArray[] = $typeRate;
			$typeArray[] = $typeTotal;
		}
		$typeData     = json_encode($typeArray, 320);
		$typeRateData = json_encode($rateArray, 320);
		$option       = <<<EOT
option = {
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'cross',
      crossStyle: {
        color: '#999'
      }
    }
  },
  legend: {
    top: 'bottom',
    data: $xData
  },
  xAxis: [
    {
      type: 'category',
      data: $xData,
      axisPointer: {
        type: 'shadow'
      }
    }
  ],
  yAxis: [
    {
      type: 'value',
      name: '不良数',
      interval: 50,
      axisLabel: {
        formatter: '{value} '
      }
    },
    {
      type: 'value',
      name: '不良影响度',
      interval: 10,
      axisLabel: {
        formatter: '{value} %'
      }
    }
  ],
  series: [
    {
      name: '不良数',
      type: 'bar',
      tooltip: {
        valueFormatter: function (value) {
          return value + '';
        }
      },
      data: $typeData
    },
    {
      name: '不良影响度',
      type: 'line',
      yAxisIndex: 1,
      tooltip: {
        valueFormatter: function (value) {
          return value + ' %';
        }
      },
      data: $typeRateData
    }
  ]
};
EOT;
		$json['html'] = $this->echarts($option);
		return json_encode($json, 320);
	}

	/**
	 * 导出
	 */
	/**
	 * 导出
	 */
	public function exportData()
	{
        $templateId = $this->get('templateId');
		if (!$this->power(self::page, 'export')) {
			$_SESSION['warn'] = '你还没有导出的权限';
        } else {
            $where  = $_SESSION[self::page]['where'];
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            $sql   = $_SESSION[self::page]['sql'];
            $result   = sqlFind($sql);
            //导出数据生成
            foreach ($result as $array){
                $column = [];
                $material     = query(self::tableTarget, " id = '$array[targetId]' ", 'typeId, typeName, name');
                $twhere       = $where . " AND targetId = '{$array['targetId']}' ";
                $mwhere       = $where . " AND targetId = '{$array['targetId']}' AND type = '{$array['type']}' ";
                $times        = static::total([
                    'table' => self::table,
                    'where' => $twhere,
                ]);
                $types        = static::total([
                    'table' => self::table,
                    'where' => $mwhere,
                ]);
                $rate         = ($types / $times * 100) . '%';
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '产品分类'=>$material['typeName'],
                            '产品名称'=>$material['name'],
                            '故障类型'=>$array['type'],
                            '故障等级'=>$array['level'],
                            '报修次数'=>$times,
                            '故障次数'=>$types,
                            '故障占比'=>$rate,
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }
			$text = $this->control['name'] . "导出了故障统计";
			$this->logText(["type" => self::page, "text" => $text]);
			$this->excelOut($title, $data, "故障统计.xlsx");
            exit(0);
		}
		header("Location:" . getenv("HTTP_REFERER"));
	}
    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'产品分类',
                    'aliasName'=>'产品分类',
                ],
                [
                    'columnName'=>'产品名称',
                    'aliasName'=>'产品名称',
                ],
                [
                    'columnName'=>'故障类型',
                    'aliasName'=>'故障类型',
                ],
                [
                    'columnName'=>'故障等级',
                    'aliasName'=>'故障等级',
                ],
                [
                    'columnName'=>'报修次数',
                    'aliasName'=>'报修次数',
                ],
                [
                    'columnName'=>'故障次数',
                    'aliasName'=>'故障次数',
                ],
                [
                    'columnName'=>'故障占比',
                    'aliasName'=>'故障占比(%)',
                ],
            ]
        };
    }
}
